<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/9
 * Time: 16:35
 */

namespace App\Api\Admin\Controllers;


use App\Exceptions\ApiException;
use App\Models\User;
use APP\Models\Media;
use App\Models\Admin\Log;
use App\Models\UserReport;

use DateTime;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class UserController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
        if ($this->user['permissions'] !== '*' && !isset($this->user['permissions']['user'])) {
            throw new ApiException('没有权限', 0);
        }
    }

    /**
     * 用户列表
     * @param Request $request
     * @return array
     */
 /*   public function lists(Request $request)
    {
        $name = $request->input('name');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;

        $where = [ ['status', 1] ];
        if ($name) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $users = User::where($where)->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get(['id', 'name', 'real_name', 'mobile', 'avatar', 'email', 'sex', 'isconfirmed', 'created_at', 'updated_at', 'praise', 'attention', 'fans','role']);
        $total = User::where($where)->count();
        $totalPage = ceil($total / $pagesize);

        return json_success('ok', ['totalPage' => $totalPage, 'list' => $users]);
    }*/
    /**
     * 用户发布的视频
     */
    public function details(Request $request){
        $user_id = IT('user_id',true, '请输入用户ID');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
        $total = D('media')->where(['uid'=>$user_id ,'is_delete'=>0, 'status'=>1 ])->count();
        $totalPage = ceil($total / $pagesize);
        $lists =  D('media')->where(['uid'=>$user_id ,'is_delete'=>0, 'status'=>1 ])->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get(['id','uid','title','media','date','cover','video_length']);

        // 获取内网视频图片链接
        $datetime = new DateTime();
        $datetime->modify('+1 day');
        foreach ($lists as &$list) {
            $list->media = getSignUrl($list->media);
            $list->cover = getSignUrl($list->cover);
        }
        unset($list);
        return json_success('ok',['total'=>$total,'totalPage'=>$totalPage,'list' => $lists]);
    }

    /**
     * 用户列表
     * @param Request $request
     * @return array
     */
    public function artnerlLists(Request $request)
    {
        $user_id = $request->input('user_id');
        $name = replace_specialChar($request->input('name'));
        $role = (int)trim($request->input('role'));
        $membership = (int)trim($request->input('membership'));
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
         if($role !==0){
             $where =  ['status'=>1, 'role'=>$role] ;
         }else{
             $where =  ['status'=>1];
         }
         if($membership !== 0){
             $where =  ['status'=>1, 'membership'=>$membership] ;
         }
        if ($name) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }elseif($user_id){
            $where[] = ['id', 'like', '%' . $user_id . '%'];
        }
        $users = User::where($where)->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get(['id', 'name', 'real_name', 'mobile', 'avatar', 'email', 'sex', 'isconfirmed', 'created_at', 'updated_at', 'praise', 'attention', 'fans','role']);
      // 获取内网视频图片链接
        foreach ($users as &$list) {
            $list->avatar = getSignUrl($list->avatar);
            $list->works  = D('media')->where(['uid'=>$list->id ,'is_delete'=>0, 'status'=>1 ])->count();
        }
        unset($list);
        $total =  User::where($where)->count();
        $totalPage = ceil($total / $pagesize);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $users]);
    }
    /**
     * 添加股东搜索列表
     */
    public function  ArtnerlData(Request $request){
       $user_id = IT('user_id');
       $mobile = IT('mobile');
       $role = (int)trim($request->input('role'));
        if($role !==0){
            $where =  ['status'=>1, 'role'=>$role] ;
        }else{
            $where =  ['status'=>1];
        }
       $data =  User::orWhere('id','=',$user_id)->where($where)->orWhere('mobile','=',$mobile)->get(['id', 'name', 'real_name', 'mobile', 'avatar', 'email', 'sex', 'isconfirmed', 'created_at', 'updated_at', 'praise', 'attention', 'fans','role']);
        return json_success('ok',$data);
    }
    /**
     * 添加用户(平台用户添加)
     * @param Request $request
     * @return array
     */
    public function  Addartnerl(Request $request){
        $user_id = IT('user_id',true,'请输入微影号');
        $role = IT('role',true,'请输入角色');
        switch ($role) {
            case 1:
                $role_type = '股东用户';
                break;
            case 2:
                $role_type = '客服';
                break;
            case 3:
                $role_type = '营销';
                break;
            default:
                $role_type = '普通用户';
                break;
        }
        $add_data =  User::where('id','=',$user_id)->update(['role'=>$role]);
        $lower_data = D('admin_users')->where('id','=',$this->user['id'])->value('lower_user');
        if($add_data){
            if($role > 1){
                D('admin_users')->where('id','=',$this->user['id'])->update(['lower_user'=>$user_id .','.$lower_data]);
            }
            (new Log)->add($this->user, '添加了【'.$user_id.'】为'.$role_type);
            return json_success('ok',$add_data);
        }else{
            return json_error('添加失败');
        }
    }
    /**
     * 添加用户(创建新用户)
     * @return array
     * @throws \Exception
     */
    public function AddUser(){
        $mobile = IT('mobile',true,'请输入手机号码');
        $password = IT('password',true,'请输入密码');
        $role = (int) IT('role',true,'请输入角色ID');
        $name = IT('name',true,'添加用户昵称');
        $sex = IT('sex',true,'请选择用户性别');
        if(!preg_match("/^\\d{11}$/",$mobile)){
            return json_error('手机号必须为11位数字');
        }
        if(!check_password_format($password)){
            return json_error('密码必须是6-16位字母数字下划线组合');
        }
        $user = DB::table('users')->where('mobile', $mobile)->first();//注册人信息
        if($user){
            return json_error('该帐号['.$mobile.']已存在');
        }
        if($role <= 1 && $role > 3){
            return json_error('请查看你添加的角色是否正确');
        }
        switch ($role) {
            case 2:
                $role_type = '客服';
                break;

            case 3:
                $role_type = '营销';
                break;
            default:
                $role_type = '普通用户';
                break;
        }
        $userInfo = [
            'mobile' => $mobile,
            'name' => $name,
            'password' => md5($password),
            'sex' => $sex,
            'status' => 1,
            'avatar'=> '',
            'created_at'    =>  date('Y-m-d H:i:s'),
            'updated_at'    =>  date('Y-m-d H:i:s'),
            'role' => $role
        ];
        $uid = DB::table('users')->insertGetId($userInfo);//插入成功返回id值
        $lower_data = D('admin_users')->where('id','=',$this->user['id'])->value('lower_user');
        if ($uid) {
            //TODO 添加成功将UID更新到user_tags表
            $tags_data =[
                'uid' => $uid,
            ];
            DB::table('user_tags')->insert($tags_data);
            D('admin_users')->where('id','=',$this->user['id'])->update(['lower_user'=> $uid .','.$lower_data]);
            //生成ticket入库
            $ticket = get_ticket($uid);
            if ($ticket) {
                (new Log)->add($this->user, '添加了用户【'.$uid.'】角色为-'.$role_type);
                return json_success('ok',['ticket' => $ticket, 'uid' => $uid]);
            }
        }else{
            return json_error('添加失败');
        }
    }

    /**
     * @return array
     * 删除用户
     */
    public function DelUser(){
        $uid = IT('uid',true,'请填写用户ID');
        $chk_user= User::where('id',$uid)->where('status','<>',0)->first();
        $role =$chk_user['role'];
         if(!$chk_user){
             return json_error('用户不存在');
         }
        switch ($role) {
            case 1:
                $role_type = '股东';
                break;
            case 2:
                $role_type = '客服';
                break;
            case 3:
                $role_type = '营销';
                break;
            default:
                $role_type = '普通用户';
                break;
        }
        $update_user = User::where('id',$uid)->update(['status'=>0]);
        if($update_user) {
            (new Log)->add($this->user, '删除了用户【' . $uid . '】角色为-' . $role_type);
            return json_success('ok');
        }else{
            return json_error('删除失败!');
        }
    }
    /**
     * @return array
     * 管理员下级用户
     */
    public function LowerUser(){
        $id = $this->user['id'];
        $data = D('admin_users')->where('id','=',$id)->first();
        $arr =explode(",",$data->lower_user);
        $list = User::whereIn('id', $arr)->distinct()->get(['id','name','avatar']);
        return json_success('ok',$list);
    }

    /**
     * @param Request $request
     * @return array
     * 举报用户列表
     */
    public function ReportUserList(Request $request){
        $page = max(1, (int) $request->input('page'));
        $pageSize = (int) $request->input('pagesize');
        $pageSize = $pageSize ?: 10;
        $offset = ($page - 1) * $pageSize;
        $total = UserReport::count();
        $totalPage = ceil($total / $pageSize);
        $fields=['wy_user_report.id','wy_user_report.report_type','wy_user_report.content','wy_user_report.report_time', 'users.id as uid','users.name'];
        $user_data =UserReport::join('users', 'users.id', '=', 'wy_user_report.report_obj_id')->skip($offset)->take($pageSize)->groupBy('wy_user_report.id')->orderBy('id', 'desc')->get($fields);
        foreach ($user_data as &$list) {
            $list->report_type = D('report_type')->where('id','=',$list->report_type)->value('name');
            $list->reports_number  = D('wy_user_report')->where('report_obj_id','=',$list->uid)->count();
        }
        unset($list);


        return json_success('ok',['total'=>$total,'totalPage' => $totalPage, 'list' => $user_data]);
    }

    /**
     * @param Request $request
     * @return array
     * 举报用户详情
     */
    public function ReportUser(Request $request){
        $uid = IT('uid', true, '请输入uid');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pageszie');
        $pagesize = $pagesize ?: 3;
        $offset = ($page - 1) * $pagesize;
        $user_fields =['id','name','mobile','created_at','avatar','role'];
        $user_info = User::where('id','=',$uid)->get($user_fields );
        foreach ($user_info as &$K) {
            $K['ReportNumber'] = UserReport::where('report_obj_id','=',$K->id)->count();;
            $K['reporttime'] = UserReport::where('report_obj_id','=',$K->id)->max('report_time');
        }
        unset($K);
        $fields=['wy_user_report.id','wy_user_report.report_type','wy_user_report.content','wy_user_report.report_time', 'users.id as userid'];;
        $lists = UserReport::join('users', 'users.id', '=', 'wy_user_report.report_obj_id')->where('wy_user_report.report_obj_id','=',$uid)->skip($offset)->take($pagesize)->get($fields);
        foreach ($lists as &$list) {
            $list->report_type = D('report_type')->where('id','=',$list->report_type)->value('name');
            $list->informant =User::where('id',$list->userid)->value('name');
        }
        unset($list);
        return json_success('ok', ['list' =>$lists,'user_info'=>$user_info]);
    }

    /*
     * 绑定/解绑 账号
     * */
    public function BindingAccount()
    {
        $admin_uid = IT('admin_uid',true,'未知管理员');
        $uid = IT('uid',true,'未知绑定用户');
        $status = IT('status',true,'未知操作状态');

        $adminRows = D('admin_users')->where('id','=',$admin_uid)->first();
        $usersRows = D('users')->where('id','=',$uid)->first();
        if(empty($adminRows))
            return json_error('管理员账号不存在');
        if(empty($usersRows))
            return json_error('用户不存在');

        $lower_user_arr = explode(',', $adminRows->lower_user);

        $optionLogStr = '账号绑定操作';
        switch ($status){
            case 1:
                $optionLogStr = '账号绑定';
                if(in_array($uid, $lower_user_arr))
                    return json_error('会员已绑定管理员账号，无需重复绑定');
                $lower_user_arr[] = $uid;
                break;
            case 2:
                $optionLogStr = '取消账号绑定';
                if(!in_array($uid, $lower_user_arr))
                    return json_error('会员未绑定管理元，无效操作');
                // 移除取消的元素
                $lower_user_arr = array_diff($lower_user_arr, [$uid]);
                break;
            default:
                return json_error('未知操作状态');
                break;
        }

        $updateResult = D('admin_users')->where('id','=',$adminRows->id)->update(['lower_user'=> empty($lower_user_arr) ? '' : trim(implode(',', $lower_user_arr), ',')]);
        if(!$updateResult)
            return json_error('账号绑定异常');

        (new Log)->add($this->user, $optionLogStr);
        return json_success('ok');
    }

    /*
     * 账号绑定-会员搜索
     *
     * */
    public function SearchAccount()
    {
        $admin_uid = IT('admin_uid',true,'未知管理员');
        $mobile = IT('mobile',true,'未知绑定用户');

        $adminRows = D('admin_users')->where('id','=',$admin_uid)->first();
        $userFeild = [DB::raw('id as uid'),'name','real_name','mobile','avatar','email','sex','isconfirmed','praise','attention','fans','role'];
        $usersRows = D('users')->select($userFeild)->where('mobile','=',$mobile)->first();

        if(!empty($usersRows)){
            if(empty($adminRows))
                return json_error('管理员账号不存在');
            if(empty($usersRows))
                return json_error('用户不存在');

            $usersRows->is_binding = 0;
            if(in_array($usersRows->uid, explode(',', $adminRows->lower_user)))
                $usersRows->is_binding = 1;

            return json_success('ok', [$usersRows]);
        }

        return json_error('数据不存在');
    }

    /*
     * 账号绑定列表
     * */
    public function BindingList()
    {
        $admin_uid = IT('admin_uid',true,'未知管理员');
        $page = IT('page');
        $pageSize = IT('pagesize');
        $adminRows = D('admin_users')->where('id','=',$admin_uid)->first();
        if(empty($adminRows))
            return json_error('管理员账号不存在');

        $pageSize = intval($pageSize) > 0 ? $pageSize : 10;
        $page = intval($page) > 0 ? $page-1 : 0;
        $lower_user_arr = explode(',', $adminRows->lower_user);

        $uidArr = array_slice($lower_user_arr, $page * $pageSize, $pageSize);
        $userFeild = [DB::raw('id as uid'),'name','real_name','mobile','avatar','email','sex','isconfirmed','praise','attention','fans','role'];
        $userList = D('users')->whereIn('id', $uidArr)->get($userFeild);

        // 设置都是绑定
        foreach ($userList as &$value)
            $value->is_binding = 1;
        return json_success('ok', $userList);
    }
}